import router from "@/router";
import {
  TUITranslateService,
  TUIUserService,
} from "@tencentcloud/chat-uikit-engine";
import { TUILogin } from "@tencentcloud/tui-core";
import { ElMessage } from "element-plus";
import { SDKAppID } from "../main";
import { TUIChatKit } from "../TUIKit";
import { vueVersion } from "../TUIKit/adapter-vue";

const loginIm = async () => {
  const token = localStorage.getItem("token");
  const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
  const sign = localStorage.getItem("sign");
  if (!token) return;
  TUIChatKit.init();
  await TUILogin.login({
    SDKAppID,
    userID: userInfo.im_id,
    userSig: sign || "",
    useUploadPlugin: true,
    framework: `vue${vueVersion}`,
  })
    .then((res: any) => {
      TUIUserService.switchUserStatus({ displayOnlineStatus: true });
    })
    .catch((error: any) => {
      ElMessage({
        message: TUITranslateService.t("登录失败"),
        grouping: true,
        type: "error",
      });
      router.replace({ name: "login" });
      localStorage.removeItem("TUIKit-userInfo");
      localStorage.removeItem("userInfo");
      localStorage.removeItem("token");
      localStorage.removeItem("sign");
      TUILogin.logout();
    });
};

export { loginIm };
